<?php

declare(strict_types=1);

namespace PHPStreamServer\Plugin\HttpServer\ReloadStrategy;

use Amp\Http\Server\Request;
use PHPStreamServer\Core\ReloadStrategy\ReloadStrategy;

/**
 * Reload worker on every $maxRequests requests.
 * To prevent all workers from restarting at the same time, you can set a $dispersionPercentage.
 * With $maxRequests = 1000 and $dispersionPercentage = 20, workers will restart after a random number of requests between 800 and 1000
 */
final class MaxRequestsReloadStrategy implements ReloadStrategy
{
    private int $requestsCount = 0;
    private readonly int $maxRequests;

    public function __construct(int $maxRequests, int $dispersionPercentage = 0)
    {
        $minRequests = $maxRequests - (int) \round($maxRequests * $dispersionPercentage * 0.01);
        $this->maxRequests = \random_int($minRequests, $maxRequests);
    }

    public function shouldReload(mixed $eventObject = null): bool
    {
        return $eventObject instanceof Request && ++$this->requestsCount > $this->maxRequests;
    }
}
